﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Golos.Users.UserCache;

namespace Golos.Web.Utils
{
    public class Token
    {
        public Guid User { get { return user; } }
        public DateTime ValidTo { get { return validTo;  } set { validTo = value; } }

        private readonly Guid user;
        private DateTime validTo;
        private readonly UserIdType userIdType;
        private readonly string uin;

        public Token(Guid user, DateTime validTo)
        {
            this.user = user;
            this.validTo = validTo;

        }

        public override string ToString()
        {
            return string.Format("[Token] UserId: '{0}', ValidTo: '{1}'", User, ValidTo.ToString("dd.MM.yyyy HH:mm:ss"));
        }

        public bool IsValid()
        {
            //LogClass.WriteDebugEntry("validate token, tokenDate=" + validTo + ", now=" + DateTime.Now);
            return ValidTo > DateTime.Now;
        }

        public string Serialize()
        {
            return string.Format("{0}\n{1}", user, validTo.Ticks);
        }

        public static Token Deserialize(string input)
        {
            string[] splits = input.Split('\n');
            if (splits.Length != 2)
                LogClass.WriteErrorEntry(string.Format("Не могу распарсить токен: {0}.", input));
            Guid user = new Guid(splits[0]);
            long ticks;
            if (!long.TryParse(splits[1], out ticks))
                LogClass.WriteErrorEntry(string.Format("Не могу распарсить токен: {0}.", input));
            DateTime validTo = new DateTime(ticks);
            return new Token(user, validTo);
        }
    }
}